/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.core.sql;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.rails.core.util.ArrayUtil;

public abstract class SQLBase {
	
	public static final String SQL = "SQL";
	public static final String FIELDS = "FIELDS";
	public static final String PARAMS = "PARAMS";
	public static final String MAX_RESULT = "MAX_RESULT";
	
	protected SQLManager sqlManager;
	
	protected String sql;
	
	protected Map<String,Object> manager;
	
	public SQLBase(SQLManager sqlManager){
		super();
		this.sqlManager = sqlManager;
	}
	
	public abstract String getSql();
	
	public abstract List<Object> getParams();
	
	public abstract List<String> getFields();
	
	public abstract int getMaxResult();
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	protected Map<String,Object> parseSqlManager(String sql){
		final Map<String,Object> sm = new HashMap<String, Object>();
		final List<String> fields = new ArrayList<String>();
		final List<Object> params = new ArrayList<Object>();
		final Map<String,Object> pms = sqlManager.getParameter();
		
		final Pattern p = Pattern.compile(":{1}[\\w\\.]+");
		final Matcher m = p.matcher(sql);
		while (m.find()) {
			final String g = m.group();
			final String f = g.replaceFirst(":", "");
			if(pms.containsKey(f)){	
				final Object pm = pms.get(f);						
				if(pm instanceof List){
					final String ins = ArrayUtil.ins((List)pm);
					sql = sql.replaceFirst(g,ins);
				}else{
					fields.add(f);
					params.add(pm);	
					sql = sql.replaceFirst(g, "?");	
				}				
			}
		}
		sm.put(SQL,sql);
		sm.put(FIELDS,fields);
		sm.put(PARAMS,params);
		sm.put(MAX_RESULT,sqlManager.getMaxResult());
		return sm;
	}
	
}
